package com.xjh.serverinspect.security;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpInputMessage;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 请求体参数处理器
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-13
 */
public class RequestBodyHandler {

    public static final String PRIVATE_KEY;

    static {
        try {
            InputStream inputStream = new ClassPathResource("RSAPrivateKey").getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            PRIVATE_KEY = bufferedReader.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] decrypt(HttpInputMessage inputMessage) {
        String s = decrypt2String(inputMessage);
        return s == null ? null : s.getBytes(StandardCharsets.UTF_8);
    }

    public static String decrypt2String(HttpInputMessage inputMessage) {
        // 获取加密的AES密钥
        List<String> headers = inputMessage.getHeaders().get("X-Encrypt");
        if (headers != null && !headers.isEmpty()) {
            String encodeAesKey = headers.get(0);
            return decrypt2String(inputMessage, encodeAesKey);
        }
        return null;
    }

    public static String decrypt2String(HttpInputMessage inputMessage, String XEncrypt) {
        // 获取加密的AES密钥
        byte[] payload;

        try {
            // 获取Payload
            payload = StreamUtils.copyToByteArray(inputMessage.getBody());

            // 对已加密的参数进行解密
            if (!StringUtils.isEmpty(XEncrypt)) {
                // 解密AES密钥
                String aesKey = RSAUtils.decryptByPrivateKey(XEncrypt, PRIVATE_KEY);
                // 解密参数
                return AESUtils.decrypt(new String(payload, StandardCharsets.UTF_8), aesKey);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new String(payload, StandardCharsets.UTF_8);
    }

}
